package com.btpj.oauth2.controller;

import com.btpj.oauth2.entity.RespBean;
import com.btpj.oauth2.entity.User;
import com.btpj.oauth2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Map;

/**
 * 自定义Oauth2获取令牌接口
 * Created by macro on 2020/7/17.
 */
@RestController
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Autowired
    UserService userService;

    /**
     * Oauth2登录认证
     */
    @PostMapping(value = "/token")
    public RespBean postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) {
        try {
            OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
            User user = (User) userService.loadUserByUsername(parameters.get("username"));
            assert oAuth2AccessToken != null;
            user.setToken(oAuth2AccessToken.getValue());
            return RespBean.success(user);
        } catch (Exception e) {
            return RespBean.error(e.getMessage());
        }
    }
}